package util

import (
	"encoding/json"
	"go.uber.org/zap"
	"io/ioutil"
	"os"
	"path/filepath"
	go_logger "platon-tools/go-service/go-logger"
)

type CustomSD struct {
	Targets []string          `json:"targets"`
	Labels  map[string]string `json:"labels"`
}

func UpdateYmlConfig(sds []CustomSD, filePath string) error {
	b, _ := json.MarshalIndent(sds, "", "    ")
	path, err := filepath.Abs(filepath.Dir(filePath))
	go_logger.Logger.Sugar().Debugf("file path: 【%s】", path)
	if err != nil {
		go_logger.Logger.Error("get file path failed", zap.Error(err))
		return err
	}
	tmpfile, err := ioutil.TempFile(path, "sd-nodes-temp")
	if err != nil {
		go_logger.Logger.Error("create temp file failed", zap.Error(err))
		return err
	}
	defer tmpfile.Close()

	_, err = tmpfile.Write(b)
	if err != nil {
		go_logger.Logger.Error("write to temp file failed", zap.Error(err))
		return err
	}

	tmpfile.Close()
	err = os.Rename(tmpfile.Name(), filePath)
	if err != nil {
		go_logger.Logger.Error("rename temp file failed", zap.Error(err))
		return err
	}

	return nil
}

func OpenSDConfig(file_all string) ([]CustomSD, error) {
	content, err := ioutil.ReadFile(file_all)
	if err != nil {
		go_logger.Logger.Sugar().Debugf("解析config.yaml读取错误: %v", err)
		return nil, err
	}

	pConfig := []CustomSD{}
	err = json.Unmarshal(content, &pConfig)
	if err != nil {
		go_logger.Logger.Error("marshal config failed", zap.Error(err))
		return nil, err
	}
	go_logger.Logger.Sugar().Debugf("config【%v】", pConfig)

	return pConfig, nil
}
